//
//  BSMainTabBar.swift
//  mySwiftWeibo
//
//  Created by apple on 16/7/18.
//  Copyright © 2016年 itcast沈庆伟. All rights reserved.
//

import UIKit

class BSMainTabBar: UITabBar {

    ///传递加号按钮button事件的闭包属性
    var composeCallBack: (() -> Void)?
    
    //按钮数量
    let itemCount:Int=5
    //布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let newItemWidth=self.frame.width / CGFloat(itemCount)
        
        //遍历
        var index = 0
        for item in self.subviews {
            //print(item)
            //[UITabBarButton class]
            let cls=NSClassFromString("UITabBarButton")!
            if item.isKindOfClass(cls){
                //print("item: \(item)")
                
                //frame
                item.frame=CGRect(x: CGFloat(index)*newItemWidth, y: 0, width: newItemWidth, height: self.frame.height)
                
                index++
                //给中间加号按钮空点位置
                if index==2{
                    index++
                }
            }
        }
        //添加加号按钮
        composeButton.frame=CGRect(x: 2*newItemWidth, y: 0, width: newItemWidth, height: self.frame.height)
    }

    //MARK: - 按钮点击事件
    func composeClick(){
        //print("composeClick")
        //view无法modal模态出一个控制器,所以用代理或闭包
        //调用闭包,传递事件
        composeCallBack?()
    }
    
    ///懒加载
    lazy var composeButton:UIButton={
        
        let button=UIButton(type: UIButtonType.Custom)
        //按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        //按钮背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //添加
        self.addSubview(button)
        
        //注册点击事件
        button.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
}
